using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Bitcoin.Store
{
    public class DiskWalletStore : IWalletStore
    {
        private FileInfo f;

        public DiskWalletStore(FileInfo f)
        {
            this.f = f;
        }

        /// <summary>
        ///     Returns a wallet deserialized from the given file.
        /// </summary>
        /// <param name="name"></param>
        /// <exception cref="IOException" />
        public Wallet Load(string name)
        {
            return LoadFromFileStream(f.OpenRead());
        }

        /// <summary>
        ///     Returns a wallet deserialized from the given file input stream.
        /// </summary>
        /// <exception cref="IOException" />
        private Wallet LoadFromFileStream(FileStream f)
        {
            var ois = new BinaryFormatter();
            return (Wallet) ois.Deserialize(f);
        }

        /// <summary>
        ///     Uses Java serialization to save the wallet to the given file.
        /// </summary>
        /// <exception cref="IOException" />
        public void Save(string name, Wallet wallet)
        {
            lock (wallet)
            {
                using (var stream = f.OpenWrite())
                {
                    SaveToFileStream(wallet, stream);
                }
            }
        }

        /// <summary>
        ///     Uses Java serialization to save the wallet to the given file stream.
        /// </summary>
        /// <exception cref="IOException" />
        private void SaveToFileStream(Wallet wallet, FileStream f)
        {
            lock (wallet)
            {
                var oos = new BinaryFormatter();
                oos.Serialize(f, wallet);
            }
        }
    }
}